<template>
	<view class="container">
		<u--form labelPosition="left" :model="formData" :rules="rules" ref="uForm">
			<view class="form-item">
				<u-form-item label="圈子名称" prop="name" labelWidth="80" borderBottom ref="item1">
					<u--input v-model="formData.name" border="none" placeholder="支持中英文。数字下划线"></u--input>
				</u-form-item>
			</view>
			<!-- <view class="form-item">
				<u-form-item label="圈子图标" prop="icon" labelWidth="80" borderBottom labelPosition="top">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"></u-upload>
				</u-form-item>
			</view> -->

			<view class="form-item">
				<u-form-item label="圈子图标" prop="icon" labelWidth="80" borderBottom labelPosition="top">
					<view class="layout-img-list">
						<view class="layout-img-list-item" v-if="formData.icon" @click="upload('icon')">
							<image :src="formData.icon" mode="" class="layout-img-list-item-image" mode="aspectFill">
							</image>
						</view>
						<view class="layout-img-list-add" @click="upload('icon')" v-else>
							<image :src="ossUrl +  '/static/image/组149.png'" mode=""></image>
						</view>
					</view>
				</u-form-item>
			</view>

			<view class="form-item" v-if="formData.type === 1">
				<u-form-item label="该圈子人群年龄" prop="target_audience" labelWidth="120" borderBottom>
					<view style="width: 100%;display: flex;align-items: center;">
						<u--input v-model.number="formData.target_audience[0]" border="none" type="number"
							placeholder="请输入" class="nums"></u--input>
						<text style="margin: 0 20rpx;">至</text>
						<u--input v-model.number="formData.target_audience[1]" border="none" type="number"
							placeholder="请输入" class="nums"></u--input>
					</view>

				</u-form-item>
			</view>

			<view class="form-item">
				<u-form-item label="提供logo素材" prop="logo" labelWidth="120">
					<view class="layout-img-list">
						<view class="layout-img-list-item" v-if="formData.logo" @click="upload('logo')">
							<image :src="formData.logo" mode="" class="layout-img-list-item-image" mode="aspectFill">
							</image>
						</view>
						<view class="layout-img-list-add" @click="upload('logo')" v-else>
							<image :src="ossUrl +  '/static/image/组149.png'" mode=""></image>
						</view>
					</view>
				</u-form-item>
			</view>

			<view class="form-item" style="margin-top: 20rpx;">
				<picker mode="selector" :range="actions" range-key="label"
					@change=" e => change(e, 'circle_classification_id', 'actions')">
					<u-form-item label="归属类别" prop="circle_classification_id" labelWidth="80"
						@click="showClass = true; hideKeyboard()">
						<u--input
							:value="formData.circle_classification_id ? actions.find(i=>i.value === formData.circle_classification_id).label : ''"
							disabled disabledColor="#ffffff" placeholder="请选择" border="none"></u--input>

						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</picker>
			</view>

			<!-- <view class="form-item" style="margin-top: 10rpx;">
				<u-form-item label="人员身份" prop="identity" labelWidth="80">
					<u--input v-model="formData.identity" disabledColor="#ffffff" placeholder="例如：游戏、教练等身份"
						border="none"></u--input>
				
				</u-form-item>
			</view> -->

			<view class="form-item" style="margin-top: 10rpx;" v-if="formData.type != 1">
				<u-form-item label="企业组织资质(执照)" prop="qualification" labelWidth="140">
					<view class="layout-img-list">
						<view class="layout-img-list-item" v-if="formData.qualification"
							@click="upload('qualification')">
							<image :src="formData.qualification" mode="" class="layout-img-list-item-image"
								mode="aspectFill">
							</image>
						</view>
						<view class="layout-img-list-add" @click="upload('qualification')" v-else>
							<image :src="ossUrl +  '/static/image/组149.png'" mode=""></image>
						</view>
					</view>
				</u-form-item>
			</view>

			<view class="form-item" style="margin-top: 10rpx;">
				<u-form-item label="圈子简介" prop="description" labelWidth="80">
					<u--textarea placeholder="写出圈子简介" v-model="formData.description" border="none"></u--textarea>
				</u-form-item>
			</view>

			<view class="form-item" style="margin-top: 10rpx;">
				<u-form-item label="身份设置" prop="identity" labelWidth="80" labelPosition="top">
					<view class="card">
						<!-- <view class="card-title">身份设置</view> -->
						<view class="card-switch flex-row-between" v-for="(it,index) in formData.identity">
							<view>
								{{it.name}}
							</view>
							<view class="flex-row">
								<u-switch v-model="it.status" :activeValue="1" :inactiveValue="0"
									@change="e => identityChange(e, it)" activeColor="#64aa6b" size="20"></u-switch>
								<view class="description">{{it.status === 0 ? '自由选择' : '需要申请'}}</view>
								<u-icon name="close" color="#e4393c" size="18" @click="delItem(index)"></u-icon>
							</view>
						</view>
						<view class="add" v-if="is_add">
							<view class="add-input">
								<input type="text" placeholder="请输入" v-model="identityValue"
									placeholder-class="add-input-plac">
							</view>
							<view class="add-r">
								<u-icon name="checkmark" color="#00e121" size="18" style="margin-right: 10rpx;"
									@click="save"></u-icon>
								<u-icon name="close" color="#e4393c" size="18" @click="del"></u-icon>
							</view>
						</view>
						<view class="add-btn flex-row-center" @click="open">+</view>
					</view>
				</u-form-item>
			</view>
			<view class="form-item" style="margin-top: 10rpx;">
				<u-form-item label="等级设置" prop="grade" labelWidth="80" labelPosition="top">
					<view class="card">
						<view class="add setting" v-for="it in formData.grade" :key="it.sort">
							<view class="add-input">
								<input type="text" placeholder="请输入" v-model="it.name"
									placeholder-class="add-input-plac">
							</view>
							<view class="add-r tx">
								lv{{it.sort}}
							</view>
						</view>
						<!-- <view class="add-btn flex-row-center">+</view> -->
					</view>
				</u-form-item>
			</view>
		</u--form>

		<view class="bottom-btn" @click="submit">提交</view>
	</view>
</template>

<script>
	import {
		uploadImg
	} from '@/common/upload.js'
	import {
		circle_classification,
		add_circle
	} from '@/common/http/api.js'
	export default {
		data() {
			return {
				formData: {
					name: '',
					icon: '',
					target_audience: ['', ''],
					logo: '',
					circle_classification_id: '',
					//identity: '',
					qualification: '',
					description: '',
					grade: [{
							"name": "学渣",
							"sort": 1
						},
						{
							"name": "学者",
							"sort": 2
						},
						{
							"name": "学霸",
							"sort": 3
						},
						{
							"name": "专家",
							"sort": 4
						},
						{
							"name": "学神",
							"sort": 5
						},
						{
							"name": "封神",
							"sort": 6
						},
					], //{ "name":" 身份1","sort": 0} 等级
					identity: [], //{ "name":" lv1","sort": 1,"status": 1} 身份设置 is_save 是否保存  status 0 关闭 1开启
					type: 1 //1: 普通圈子, 2: 企业圈子, 3: 组织圈子
				},
				rules: {
					name: {
						type: 'string',
						required: true,
						message: '请填写',
						trigger: ['blur', 'change'],
					},
					icon: {
						type: 'string',
						required: true,
						message: '请上传',
						trigger: ['blur', 'change'],
					},
					target_audience: {
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							if (this.formData.type === 1) {
								if (!(this.formData.target_audience[0] && this.formData.target_audience[1])) {
									return callback(new Error('请输入！'));
								}
							}
							return callback();
						},
						message: '请输入',
						trigger: ['blur', 'change'],
					},
					logo: {
						type: 'string',
						required: true,
						message: '请上传',
						trigger: ['blur', 'change'],
					},
					circle_classification_id: {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							return !!this.formData.circle_classification_id
						},
						message: '请选择',
						trigger: ['blur', 'change'],
					},
					identity: {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							if (value.length === 0) {
								return callback(new Error('请添加身份设置！'));
							}

							let status = true
							value.forEach(i => {
								if (value.filter(j => j.name === i.name).length > 1) {
									status = false
								}
							})

							if (!status) {
								return callback(new Error('不能有重复的身份名字！'));
							}
							return callback();

						},
						// message: '请选择',
						trigger: ['blur', 'change'],
					},
					grade: {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过

							let status = true
							value.forEach(i => {
								if (value.filter(j => j.name === i.name).length > 1) {
									status = false
								}
							})

							if (!status) {
								return callback(new Error('不能有重复的等级名字！'));
							}
							return callback();

						},
						// message: '请选择',
						trigger: ['blur', 'change'],
					},
					qualification: {
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							if (!(this.formData.type != 1 && this.formData.qualification)) {
								return callback(new Error('请上传！'));
							}
							return callback();
						},
						message: '请上传',
						trigger: ['blur', 'change'],
					},
					description: {
						type: 'string',
						required: true,
						message: '请输入',
						trigger: ['blur', 'change'],
					},
				},
				actions: [],
				identityValue: '',
				is_add: false
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad(e) {
			if (e.type) {
				this.formData.type = Number(e.type)
			}
			circle_classification().then(res => {
				let arr = []
				if (e.type == 1) { //兴趣
					res.data.forEach(item => {
						if (item.name != '企业（需申请加入）' && item.name != '组织（需申请加入）') {
							arr.push({
								label: item.name,
								value: item.id
							})
						}
					})
					this.actions = arr

				} else if (e.type == 2) {
					res.data.forEach(item => {
						if (item.name == '企业（需申请加入）') {
							arr.push({
								label: item.name,
								value: item.id
							})
							this.formData.circle_classification_id = item.id
						}
					})
					this.actions = arr
				} else {
					res.data.forEach(item => {
						if (item.name == '组织（需申请加入）') {
							arr.push({
								label: item.name,
								value: item.id
							})
							this.formData.circle_classification_id = item.id
						}
					})
					this.actions = arr
				}


			})
		},
		methods: {
			delItem(index) {
				this.formData.identity.splice(index, 1)
			},
			identityChange(e, it) {
				console.log('e', e)
			},
			open() {
				this.identityValue = ''
				this.is_add = true
			},
			save() {
				this.formData.identity.push({
					name: this.identityValue,
					status: 0
				})
				this.del()
			},
			del() {
				this.identityValue = ''
				this.is_add = false
			},
			submit() {
				this.$refs.uForm.validate().then(res => {
					// uni.$u.toast('校验通过')
					uni.showLoading({
						mask: true,
						title: "创建中"
					})
					let data = {
						...this.formData,
						identity: JSON.stringify(this.formData.identity.map((i, index) => ({
							...i,
							sort: index + 1
						}))),
						grade: JSON.stringify(this.formData.grade)
					}
					add_circle(data).then(res => {
						uni.hideLoading()
						uni.$u.toast("创建成功")
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}, 1500)
					})
				})
			},
			change(e, field, range) {
				this.formData[field] = this[range][e.detail.value].value
			},
			upload(field) {
				uploadImg().then(res => {
					console.log('res', res)
					this.formData[field] = res.data.url
				})
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			classSelect(e) {
				this.formData.calss = e.name
			},
			identitySelect(e) {
				this.formData.identity = e.name
			},
			certificationSelect(e) {
				this.formData.certification = e.name
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
		},

	}
</script>

<style lang='scss' scoped>
	.layout-img-list {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		margin-top: 10rpx;

		&>view {
			margin-right: 15rpx;
		}
	}

	.layout-img-list-add {
		width: 151rpx;
		height: 151rpx;
		border-radius: 20rpx;
		/* 	border: 1px solid #999999; */
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.layout-img-list-item {
		width: 151rpx;
		height: 151rpx;
		position: relative;

		image {
			width: 100%;
			height: 100%;
		}

		.layout-img-list-item-image {
			border-radius: 20rpx;
		}

		.layout-img-list-item-del {
			width: 38rpx;
			height: 38rpx;
			position: absolute;
			top: -15rpx;
			right: -15rpx;
			z-index: 2;
		}
	}

	.container {
		background-color: #f7f7f9;
		min-height: 100vh;
		padding-bottom: 30rpx;

		.form-item {
			background-color: #fff;
			padding: 0 40rpx;
		}

		.bottom-btn {
			width: 80%;
			text-align: center;
			background-color: #6aaf74;
			color: #fff;
			padding: 20rpx 0;
			margin: 0 auto;
			border-radius: 50rpx;
			margin-top: 20rpx;
		}
	}

	.card {
		border-radius: 20rpx;
		background-color: #fff;
		padding: 20rpx;

		.card-title {
			font-size: 28rpx;
			color: #000;
			border-bottom: 1px solid #eee;
			padding-bottom: 20rpx;
		}

		.description {
			font-size: 24rpx;
			color: #ccc;
			margin-left: 10rpx;
			margin-right: 10rpx;
		}

		.card-switch {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #000;
		}

		.add-btn {
			margin-top: 10rpx;
			width: 400rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background-color: #ededed;
			color: #8f8f8f;
		}
	}

	.add {
		width: 100%;
		display: flex;
		align-items: center;
		padding: 10rpx 0;

		.add-input {
			flex: 1;
			margin-right: 10rpx;
			height: 60rpx;

			input {
				width: 100%;
				height: 100%;
				box-sizing: border-box;
				padding: 0 10rpx;
				font-size: 22rpx;
				color: #000;
				border: 1rpx solid #ccc;
				border-radius: 10rpx;
			}

			.add-input-plac {
				font-size: 22rpx;
				color: #000;
			}
		}

		.add-r {
			display: flex;
			align-items: center;
		}

		.tx {
			color: #8f8f8f;
		}
	}

	.setting {
		.add-input {
			width: 40%;
			flex: none;
		}

		.add-r {}
	}

	.nums {
		flex: 1;
	}
</style>